package com.example.houselease.repo.impl;

import com.example.houselease.pojo.vo.AdminDetailVO;
import com.example.houselease.pojo.vo.AdminListVO;
import com.example.houselease.repo.IAdminRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 管理员数据 redis缓存配置接口 实现类
 * @author sf
 * @version 0.0.1
 * */
@Service
@Slf4j
public class AdminRedisRepositoryImpl implements IAdminRedisRepository {

    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public List<AdminListVO> list() {
        return list(0,-1);
    }

    public List<AdminListVO> list(int start, int end){
        log.debug("开始从redis中查询【管理员列表】数据，start：{}，end：{}",start,end);
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        List<Serializable> result = ops.range(ADMIN_LIST_KEY, 0, -1);
        List<AdminListVO> adminListVOS = new ArrayList<>();
        result.forEach(obj -> adminListVOS.add((AdminListVO) obj));
        return adminListVOS;
    }

    @Override
    public void deleteAll() {
        log.debug("开始执行【从redis删除管理员缓存数据】");
        //获取所有存储在redis中管理员数据的keys
        SetOperations<String, Serializable> ops = redisTemplate.opsForSet();
        Set<Serializable> result = ops.members(ADMIN_ALL_KEYS);
        Set<String> adminKeys = new HashSet<>();
        result.forEach(i -> adminKeys.add((String) i));
        redisTemplate.delete(adminKeys);
    }

    @Override
    public void save(List<AdminListVO> adminListVOS) {
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        adminListVOS.forEach(i -> ops.rightPush(ADMIN_LIST_KEY,i));//添加所有管理员数据到redis中
        redisTemplate.opsForSet().add(ADMIN_ALL_KEYS,ADMIN_LIST_KEY);//添加管理员列表key到redis
    }

    @Override
    public void save(AdminDetailVO adminDetailVO) {
        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        ops.set(ADMIN_ITEM_KEY_PREFIX+adminDetailVO.getId(),adminDetailVO);//向redis中添加，管理员详情数据
    }

    @Override
    public AdminDetailVO get(Long id) {
        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        return (AdminDetailVO) ops.get(ADMIN_ITEM_KEY_PREFIX+id);
    }
}
